import axios from '../utils/request.js'
import {
	getSession,
	setSession
} from '../utils/dataStorage.js'
import qs from 'qs' //引入qs


export function dictionaryMap(categoryCode) {
	return new Promise((resolve, reject) => {
		let dictionary = getSession(categoryCode);
		if (dictionary) {//如果缓存有,且未过期,则返回缓存值
			try {
				dictionary = JSON.parse(dictionary);
				if (dictionary && dictionary["expired"] && parseInt(dictionary["expired"]) > parseInt(new Date().getTime() / 1000)) {
					return resolve(dictionary.content);					
				}
			} catch (e) {}
		}
		//如果缓存没有值  或  缓存值过期,则向后台请求, 将请求结果重新缓存,并返回
		dictionaryRequest(categoryCode).then(data => {
			if (data) {
				var dicMap = {};
				data.forEach(function(item) {
					dicMap[item["itemValue"]] = item["itemName"];
				});
				let expired = parseInt(new Date().getTime() / 1000) + 300; //设置过期时间 5 * 60 (5分钟)
				dictionary = {
					"expired": expired,
					"content": dicMap
				};
				setSession(categoryCode, JSON.stringify(dictionary));
				return resolve(dictionary.content);				
			}
		}).catch(exception => {
			reject({});
		});
	});
}

export async function dictionaryRequest(categoryCode) {
	return await axios.get('/sys/dictionary/code/' + categoryCode);
}

export function dictionaryList(params) {
	return axios.get('/sys/dictionary/list?' + qs.stringify(params));
}

export function dictionarySave(dictionary) {
	return axios.post('/sys/dictionary/save', dictionary);
}

export function dictionaryDelete(primaryKey) {
	return axios.delete('/sys/dictionary/' + primaryKey);
}
